package cn.zmwh.common.job;

import cn.hutool.core.util.StrUtil;
import cn.zmwh.common.job.config.XxlJobProperties;
import cn.zmwh.common.job.properts.XxlAdminProperties;
import cn.zmwh.common.job.properts.XxlExecutorProperties;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * xxl-job自动装配
 *
 * @author dmzmwh
 * @time: 2020-03-11 12:42 、
 */
@Slf4j
@Configuration
@ComponentScan(value = {"cn.zmwh.common.job.config", "cn.zmwh.common.job.handler"})
public class XxlJobConfiguration {

    /**
     * 服务名称 包含 XXL_JOB_ADMIN 则说明是 Admin
     */
    private static final String XXL_JOB_ADMIN = "xxl-job-admin";

    /**
     * 配置xxl-job 执行器，提供自动发现 xxl-job-admin 能力
     *
     * @param xxlJobProperties xxl 配置
     * @return
     */
    @Bean
    public XxlJobSpringExecutor xxlJobSpringExecutor(XxlJobProperties xxlJobProperties, Environment environment) {
        log.info("xxl-job-admin 自动装配");
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        XxlExecutorProperties executor = xxlJobProperties.getExecutor();
        XxlAdminProperties admin = xxlJobProperties.getAdmin();

        // 应用名默认为服务名
        String appName = executor.getAppname();
        if (StrUtil.isBlank(appName)) {
            appName = environment.getProperty("spring.application.name");
        }
        xxlJobSpringExecutor.setAppname(appName);
        xxlJobSpringExecutor.setAddress(executor.getAddress());
        xxlJobSpringExecutor.setIp(executor.getIp());
        xxlJobSpringExecutor.setPort(executor.getPort());
        xxlJobSpringExecutor.setLogPath(executor.getLogPath());
        xxlJobSpringExecutor.setLogRetentionDays(executor.getLogRetentionDays());
        xxlJobSpringExecutor.setAccessToken(admin.getAccessToken());
//		xxlJobSpringExecutor.setTimeout(admin.getTimeout());
        String addresses = admin.getAddresses();
        if (!addresses.contains(XXL_JOB_ADMIN)) {
            addresses = addresses.concat("/").concat(XXL_JOB_ADMIN);
        }
        xxlJobSpringExecutor.setAdminAddresses(addresses);

        return xxlJobSpringExecutor;
    }

}
